<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <div class="search-wrapper">
      <el-form ref="queryFormRef" :model="deviceQueryForm" :inline="true">
        <el-form-item :label="$t('device.deviceName')" prop="id">
          <el-select
              v-model="deviceQueryForm.id"
              :placeholder="
              $t('common.placeholderSelect') + $t('device.deviceName')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in deviceList"
                :key="index"
                :label="locale ? item.deviceCnName : item.deviceEnName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="search" type="primary" icon="Search">{{
              $t("common.search")
            }}
          </el-button>
          <el-button @click="adddevice" type="primary" icon="Plus">{{
              $t("common.add")
            }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 2. 引入通用表单对话框组件 -->
    <CommonFormDialog
        :dialog-title="dialogTitle"
        v-model="dialogVisible"
        :dialog-width="dialogWidth"
        :form-data="deviceForm"
        :form-rules="deviceRules"
        :submit-loading="submitLoading"
        @close="close"
        @cancel="cancel"
        @submit="handleFormSubmit"
        @before-close="handleDialogBeforeClose"
        ref="dialogRef"
    >
      <!-- 2.1 自定义表单项（插槽：标签的“名称”和“排序”） -->
      <template #formItems>
        <el-form-item :label="$t('device.deviceCnName')" prop="deviceCnName">
          <el-input
              v-model="deviceForm.deviceCnName"
              :placeholder="
              $t('common.placeholderInput') + $t('device.deviceCnName')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('device.deviceEnName')" prop="deviceEnName">
          <el-input
              v-model="deviceForm.deviceEnName"
              :placeholder="
              $t('common.placeholderInput') + $t('device.deviceEnName')
            "
              clearable
              maxLength="50"
          />
        </el-form-item>
        <el-form-item :label="$t('device.unitNum')" prop="unitNum">
          <el-input-number
              v-model="deviceForm.unitNum"
              :placeholder="
              $t('common.placeholderInput') + $t('device.unitNum')
            "
              :min="1"
              :max="99999"
          />
        </el-form-item>
        <el-form-item :label="$t('device.sysInfoCategory')" prop="sysInfoCategory">
          <el-select
              v-model="deviceForm.sysInfoCategory"
              :placeholder="
              $t('common.placeholderSelect') + $t('device.sysInfoCategory')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in sysInfoCategoryEnums"
                :key="index"
                :label="locale ? item.cndesc : item.endesc"
                :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('device.deviceEnable')" prop="isEnable">
          <el-select
              v-model="deviceForm.isEnable"
              :placeholder="
              $t('common.placeholderSelect') + $t('device.deviceEnable')
            "
              clearable
          >
            <el-option
                v-for="(item, index) in isEnableList"
                :key="index"
                :label="locale ? item.cndesc : item.endesc"
                :value="item.code"
            />
          </el-select>
        </el-form-item>
        <!-- 可扩展：如需其他表单项（如“颜色”“描述”），直接在这里添加 -->
      </template>
    </CommonFormDialog>

    <el-card>
      <el-row>
        <el-col :span="24">
          <el-card
          ><!-- 数据表格 -->
            <el-table
                max-height="600"
                :data="tableData"
                style="width: 100%"
                @selection-change="handleSelectionChange"
            >
              <el-table-column
                  :label="$t('common.sn')"
                  type="index"
                  width="150"
              />
              <el-table-column
                  :label="$t('device.gatewayId')"
                  align="center"
                  prop="deviceEnName"
              >
                <template #default="scope">
                  {{getgatewayNameByGatewayId(scope.row.gatewayId)}}
                </template>
              </el-table-column>
              <el-table-column
                  :label="$t('device.deviceCnName')"
                  align="center"
                  prop="deviceCnName"
              />
              <el-table-column
                  :label="$t('device.deviceEnName')"
                  align="center"
                  prop="deviceEnName"
              />
              <el-table-column
                  :label="$t('device.unitNum')"
                  align="center"
                  prop="unitNum"
              />
              <el-table-column
                  :label="$t('device.sysInfoCategory')"
                  align="center"
                  prop="sysInfoCategory"
              >
                <template #default="scope">
                  {{getSysInfoCategoryNameBySysInfoCategoryId(scope.row.sysInfoCategory)}}
                </template>
              </el-table-column>
              <el-table-column
                  :label="$t('common.createTime')"
                  align="center"
                  prop="createTime"
              />
              <el-table-column
                  :label="$t('common.updateTime')"
                  align="center"
                  prop="updateTime"
              />
              <el-table-column
                  label="操作"
                  align="center"
                  width="200"
                  fixed="right"
              >
                <template #default="scope">
                  <el-button
                      type="primary"
                      link
                      icon="Edit"
                      @click="updatedevice(scope.row)"
                  >{{ $t("common.edit") }}
                  </el-button
                  >
                  <el-button
                      type="danger"
                      link
                      icon="Delete"
                      @click="deletedevice(scope.row)"
                  >{{ $t("common.delete") }}
                  </el-button
                  >
                  <el-button
                      type="default"
                      link
                      @click="goPoint(scope.row)"
                  >{{ $t("common.point") }}
                  </el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <div class="pagination-container">
              <el-pagination
                  v-model:current-page="deviceQueryForm.pageNum"
                  v-model:page-size="deviceQueryForm.pageSize"
                  :page-sizes="[10, 20, 30, 50]"
                  :total="total"
                  :background="true"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import {
  getdeviceListApi,
  getdevicePageApi,
  adddeviceApi,
  updatedeviceApi,
  deldeviceApi,
} from "@/api/ems/device/device.ts";
import {
  getgatewayListApi,
} from "@/api/ems/gateway/gateway.ts";
import {getEnumListByType} from "@/api/enums";
import {EmsCommonEnums} from "@/enum/common/EmsCommonEnums"
import {ElMessage, ElMessageBox, ElLoading} from "element-plus";
import {useI18n} from "vue-i18n";
import CommonFormDialog from "@/components/Modal/basicModal.vue"; // 引入通用组件
import {reactive, ref, onMounted, onUnmounted, watch, nextTick} from "vue";
import {useRoute, useRouter} from "vue-router";

const tableData = ref(); //表格数组
const locale = ref(window.localStorage.getItem("locale") == "zh-CN");
const total = ref(0);
const dialogWidth = ref("600px");
// 1. 对话框状态
const dialogVisible = ref(false); // 对话框是否显示
const router = useRouter();
const route = useRoute();
const submitLoading = ref(false); // 提交按钮加载状态
const dialogRef = ref(); // 通用对话框组件引用
const {t} = useI18n();
const dialogTitle = ref(); // 对话框标题
// 2. 场站查询表单数据
const deviceQueryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  id: "", // 设备Id
  gatewayId: null,//场站ID
});
// 2. 场站新增表单数据
const deviceForm = reactive({
  deviceCnName: "", // 设备中文名称
  deviceEnName: "", // 设备英文名称
  unitNum: null,//单元数量
  gatewayId: null,  // 网关ID
  sysInfoCategory: null,//系统信息分类(0:sys,1:unit)
  isEnable: null, //设备是否可用
});
// 3. 标签表单校验规则
const deviceRules = reactive({
  deviceCnName: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
    {max: 50, message: t("common.inputRule"), trigger: "blur"},
  ],
  deviceEnName: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
    {max: 50, message: t("common.inputRule"), trigger: "blur"},
  ],
  unitNum: [
    {required: true, message: t("common.placeholderInput"), trigger: "blur"},
  ],
  sysInfoCategory: [
    {required: true, message: t("common.placeholderSelect"), trigger: "change"},
  ],
  isEnable: [
    {required: true, message: t("common.placeholderSelect"), trigger: "change"},
  ],
});
//设备列表
const deviceList = ref([]);
//可用列表枚举
const isEnableList = ref([]);
//系统单元分类枚举
const sysInfoCategoryEnums = ref([]);
//场站列表
const gatewayList = ref([]);
//获取mqtt服务器配置枚举列表
const getEnumListByTypes = async (type) => {
  let res = await getEnumListByType({type: type});
  if (type == EmsCommonEnums.CommonEnable) {
    isEnableList.value = res.data;
  }
  if (type == EmsCommonEnums.CommonEmsSyCategorEnum) {
    sysInfoCategoryEnums.value = res.data;
  }
}
//根据场站ID获取场站名称
const getStationNameByStationId = (id) => {
  stationList.value?.forEach(item => {
    if (item.id == id) {
      return locale ? item.stationCnName : item.stationEnName;
    }
  })
}

//查询
const search = () => {
  getSelectPage();
};
const handleSizeChange = (val) => {
  deviceQueryForm.pageSize = val;
  getSelectPage();
};
const handleCurrentChange = (val) => {

  deviceQueryForm.pageNum = val;
  getSelectPage();
};
const getSelectPage = () => {
  getdevicePageApi(deviceQueryForm).then((res) => {
    tableData.value = res.data.records;
    total.value = res.data.total;
  });
};
const getdeviceList = () => {
  getdeviceListApi(deviceQueryForm).then((res) => {
    deviceList.value = res.data;
  });
};

// 关闭对话框时，触发 update:modelValue 事件
const close = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
// 关闭对话框时，触发 update:modelValue 事件
const cancel = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};
//新增调出弹框
const adddevice = () => {
  dialogVisible.value = true;
  Object.assign(deviceForm, {
    id: null,
    deviceCnName: "", // 设备中文名称
    deviceEnName: "", // 设备英文名称
    unitNum: null,//单元数量
    gatewayId: gatewayId.value,  // 网关ID
    sysInfoCategory: null,//系统信息分类(0:sys,1:unit)
    isEnable: null, //设备是否可用
  });
  dialogTitle.value = t("device.deviceAdd");
};
//修改调出弹框
const deviceId = ref();
const updatedevice = (row) => {
  dialogTitle.value = t("device.deviceUpdate");
  dialogVisible.value = true;
  deviceId.value = row.id;
  Object.assign(deviceForm, row);
};
const handleDialogBeforeClose = () => {
  dialogVisible.value = false; // 通知父组件将 dialogVisible 设为 false
};

//提交数据
const handleFormSubmit = () => {
  if (dialogTitle.value == t("device.deviceAdd")) {
    adddeviceApi(deviceForm).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.error"));
      }
    });
  } else {
    updatedeviceApi(Object.assign(deviceForm)).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
        dialogVisible.value = false;
      } else {
        ElMessage.success(t("common.error"));
      }
    });
  }
};
//跳转点表页面
const goPoint = (row) => {
  router.push({path: "/ems/point", query: {deviceId: row.id}})
}
//删除数据
const deletedevice = (row) => {
  ElMessageBox.confirm(
      `是否确认删除`,
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
  ).then(() => {
    deldeviceApi(row.id).then((res) => {
      if (res.code == 200) {
        ElMessage.success(t("common.success"));
        getSelectPage();
      } else {
        ElMessage.success(t("common.error"));
      }
    });
  });
};
//获取网关列表
const getgatewayList = () => {
  getgatewayListApi().then((res) => {
    gatewayList.value = res.data;
  });
};
//根据ID获取网关名称
const getgatewayNameByGatewayId = (id) => {
  let res = "";
  gatewayList.value?.forEach(item => {
    if (item.id == id) {
      res = locale ? item.gatewayCnName : item.gatewayEnName;
    }
  })
  return  res
}
//根据ID获取信息分类名称
const getSysInfoCategoryNameBySysInfoCategoryId = (id) => {
  let res = "";
  sysInfoCategoryEnums.value?.forEach(item => {
    if (item.code == id) {
      res = locale ? item.cndesc : item.endesc;
    }
  })
  return  res;
}
//场站ID（路由跳转的参数ID）
const gatewayId = ref();
onMounted(() => {
  gatewayId.value = route.query.gatewayId;
  deviceQueryForm.gatewayId = gatewayId.value;
  deviceForm.gatewayId = gatewayId.value;
  getSelectPage();
  getdeviceList();
  getgatewayList();
  getEnumListByTypes(EmsCommonEnums.CommonEnable);
  getEnumListByTypes(EmsCommonEnums.CommonEmsSyCategorEnum)
});
onUnmounted(() => {
});
</script>
<style lang="scss" scoped>
:root[data-theme="dark"] {
  .app-container {
    :deep(.el-dialog) {
      .el-form {
        .el-input__wrapper {
          box-shadow: 0 0 0 1px var(--el-border-color) inset;
        }
      }
    }
  }
}

.app-container {
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  :deep(.el-dialog) {
    .el-dialog__body {
      padding: 20px 40px;
    }

    .el-form {
      .el-form-item {
        margin-bottom: 22px;

        &:last-child {
          margin-bottom: 0;
        }

        .el-form-item__label {
          font-weight: 500;
          padding-right: 20px;
        }
      }

      .el-select {
        width: 100%;
      }
    }
  }
}
</style>
